'use client';

import { useState } from 'react';
import { Form, Input, Select, Button, Divider, message, Radio, Tooltip, Tabs, Card, Switch, Badge } from 'antd';
import { ArrowRightOutlined, QuestionCircleOutlined } from '@ant-design/icons';
import { ContainerConfig, DEFAULT_CONFIGS, ContainerEnv, developmentScenes } from '../../config/devcontainer';
import EnvSelector from './EnvSelector';
import ContainerSettings from './ContainerSettings';
import {
  IconCpu,
  IconBrandJavascript,
  IconTerminal2,
  IconNetwork,
  IconCurrencyBitcoin,
  IconDeviceGamepad2,
  IconChartBar,
  IconTopologyStar,
  IconShieldLock,
  IconDevices
} from './SceneIcons';
import WorkflowDiagram from './WorkflowDiagram';

// 场景与图标、主色映射
const sceneIconColorMap = [
  { icon: IconCpu, color: '#2563eb' }, // 系统编程-蓝
  { icon: IconBrandJavascript, color: '#f59e42' }, // WebAssembly-橙
  { icon: IconTerminal2, color: '#64748b' }, // 命令行工具-灰
  { icon: IconNetwork, color: '#10b981' }, // 网络编程-绿
  { icon: IconCurrencyBitcoin, color: '#fbbf24' }, // 区块链-金
  { icon: IconDeviceGamepad2, color: '#a21caf' }, // 游戏开发-紫
  { icon: IconChartBar, color: '#0ea5e9' }, // 数据分析-青
  { icon: IconTopologyStar, color: '#f43f5e' }, // 分布式-红
  { icon: IconShieldLock, color: '#f87171' }, // 安全-深红
  { icon: IconDevices, color: '#22d3ee' }, // 跨平台-蓝绿
];

const REPO_PLATFORMS = [
  { label: 'GitHub', value: 'github' },
  { label: 'Gitee', value: 'gitee' },
  { label: 'AtomGit', value: 'atomgit' },
];

export default function ConfigForm() {
  const [env, setEnv] = useState<ContainerEnv>('dev');
  const [config, setConfig] = useState<Partial<ContainerConfig>>(DEFAULT_CONFIGS['dev']);
  const [sceneId, setSceneId] = useState<number>(developmentScenes[0].id);
  const [loading, setLoading] = useState(false);
  const [storageType, setStorageType] = useState<'local' | 'repo'>('repo');
  const [projectName, setProjectName] = useState('');
  const [repoPlatform, setRepoPlatform] = useState('github');
  const [repoUrl, setRepoUrl] = useState('');
  const [region, setRegion] = useState<'china' | 'global'>('china');
  const [activeTab, setActiveTab] = useState('base');

  // 系统配置字段变更
  const handleSystemChange = (field: keyof ContainerConfig['system'], value: any) => {
    setConfig(prev => {
      const prevSystem = prev.system || { timezone: '', locale: { lang: '', lcAll: '' }, mirrors: { apt: '', rustup: '', cargo: '' } };
      let newSystem = { ...prevSystem };
      if (field === 'locale') {
        newSystem.locale = value;
      } else {
        newSystem[field] = value;
      }
      return {
        ...prev,
        system: newSystem
      };
    });
  };

  // 镜像源变更
  const handleMirrorChange = (field: keyof ContainerConfig['system']['mirrors'], value: string) => {
    setConfig(prev => {
      const prevSystem = prev.system || { timezone: '', locale: { lang: '', lcAll: '' }, mirrors: { apt: '', rustup: '', cargo: '' } };
      const prevMirrors = prevSystem.mirrors || { apt: '', rustup: '', cargo: '' };
      return {
        ...prev,
        system: {
          ...prevSystem,
          mirrors: {
            ...prevMirrors,
            [field]: value
          }
        }
      };
    });
  };

  // 环境切换
  const handleEnvChange = (newEnv: ContainerEnv) => {
    setEnv(newEnv);
    setConfig(DEFAULT_CONFIGS[newEnv]);
  };

  // 选择开发场景
  const handleSceneChange = (id: number) => {
    setSceneId(id);
    // 这里可以根据场景做后续配置联动
  };

  // 提交（暂时只做提示）
  const handleSubmit = async () => {
    message.info('请继续完善表单后再生成配置');
  };

  // 标签顺序
  const tabOrder = ['base', 'container', 'devtools', 'workflow', 'preview'];
  // 下一步切换标签
  const handleNext = () => {
    const idx = tabOrder.indexOf(activeTab);
    if (idx !== -1 && idx < tabOrder.length - 1) {
      setActiveTab(tabOrder[idx + 1]);
    }
  };

  // 容器配置变更处理
  const handleContainerSettingsChange = (values: any) => {
    setConfig(prev => ({
      ...prev,
      container: {
        ...prev.container,
        ...values
      }
    }));
  };

  return (
    <div className="flex flex-col flex-1">
      <Tabs
        activeKey={activeTab}
        onChange={setActiveTab}
        type="card"
        tabBarGutter={8}
        className="flex-1 flex flex-col h-full"
        items={[
          {
            key: 'base',
            label: '基础设置',
            children: (
              <div className="flex-1 p-4 flex flex-col">
                <Form layout="vertical" className="flex-1 flex flex-col">
                  <div className="flex-1">
                    {/* 1. 选择开发场景 */}
                    <Form.Item label="选择开发场景" className="mb-6">
                      <div className="scene-grid">
                        {developmentScenes.map((scene, idx) => {
                          const selected = sceneId === scene.id;
                          const { icon: Icon, color } = sceneIconColorMap[idx] || {};
                          return (
                            <div key={scene.id} className="flex flex-col w-full">
                              <div
                                className={`flex flex-row items-center justify-center py-2.5 px-3 rounded-lg border-2 transition-all cursor-pointer select-none w-full
                                  ${selected ? '' : 'border-gray-200 bg-white hover:border-gray-300'}
                                  hover:shadow-md`}
                                style={{
                                  background: selected ? color : '#fff',
                                  color: selected ? '#fff' : color,
                                  borderColor: selected ? color : undefined,
                                  boxShadow: selected ? `0 2px 8px 0 ${color}33` : undefined,
                                }}
                                onClick={() => handleSceneChange(scene.id)}
                              >
                                <Icon width={24} height={24} style={{ color: selected ? '#fff' : color, marginRight: 12 }} />
                                <span className={`font-medium ${selected ? 'text-white' : ''}`}>{scene.name}</span>
                              </div>
                              <div className="text-sm text-gray-500 mt-1.5 px-1">
                                {scene.description}
                              </div>
                            </div>
                          );
                        })}
                      </div>
                    </Form.Item>

                    <Divider className="my-6" />

                    {/* 2. 选择项目存储方式 */}
                    <Form.Item label="选择项目存储方式" className="mb-6">
                      <Radio.Group
                        value={storageType}
                        onChange={e => setStorageType(e.target.value)}
                        className="mb-3"
                      >
                        <Radio.Button value="repo">代码仓库</Radio.Button>
                        <Radio.Button value="local">本地存储</Radio.Button>
                      </Radio.Group>
                      {storageType === 'local' ? (
                        <div className="space-y-3">
                          <Form.Item label="项目名称" required>
                            <Input
                              value={projectName}
                              onChange={e => setProjectName(e.target.value)}
                              placeholder="请输入项目名称"
                              maxLength={32}
                            />
                          </Form.Item>
                        </div>
                      ) : (
                        <div className="space-y-3">
                          <Form.Item label="仓库平台" required>
                            <Select
                              value={repoPlatform}
                              onChange={setRepoPlatform}
                              style={{ width: 160 }}
                            >
                              {REPO_PLATFORMS.map(p => (
                                <Select.Option key={p.value} value={p.value}>{p.label}</Select.Option>
                              ))}
                            </Select>
                          </Form.Item>
                          <Form.Item label="仓库地址" required>
                            <Input
                              value={repoUrl}
                              onChange={e => setRepoUrl(e.target.value)}
                              placeholder="请输入代码仓库地址"
                            />
                          </Form.Item>
                          <div className="text-xs text-yellow-600">
                            请确保你有该仓库的访问权限，否则无法拉取或推送代码。
                          </div>
                        </div>
                      )}
                    </Form.Item>

                    <Divider className="my-6" />

                    {/* 3. 选择地区 */}
                    <Form.Item label="选择地区" className="mb-6">
                      <Radio.Group
                        value={region}
                        onChange={e => setRegion(e.target.value)}
                        className="mb-2"
                      >
                        <Radio.Button value="china">中国地区（自动应用中文字符集）</Radio.Button>
                        <Radio.Button value="global">国际地区</Radio.Button>
                      </Radio.Group>
                      <div className="text-xs text-gray-500 mt-1">
                        选择中国地区将自动为容器配置中文字符集和国内镜像源。
                      </div>
                    </Form.Item>
                  </div>

                  {/* 底部按钮 */}
                  <div className="flex justify-end border-t border-gray-100 mt-auto pt-4">
                    <Button type="primary" size="large" onClick={handleNext}>
                      下一步 <ArrowRightOutlined />
                    </Button>
                  </div>
                </Form>
              </div>
            ),
          },
          {
            key: 'container',
            label: '容器设置',
            children: (
              <div className="flex-1 p-4 flex flex-col">
                <ContainerSettings
                  value={config.container}
                  onChange={handleContainerSettingsChange}
                  onNext={handleNext}
                />
              </div>
            ),
          },
          {
            key: 'devtools',
            label: '开发设置',
            children: (
              <div className="flex-1 p-4 flex flex-col">
                <Form layout="vertical" className="flex-1">
                  {/* IDE 选择 */}
                  <Card className="mb-6">
                    <div className="flex items-center justify-between mb-4">
                      <div className="flex items-center">
                        <span className="text-lg font-medium text-blue-600">IDE 配置</span>
                        <Badge count="IDE" style={{ backgroundColor: '#2563eb', marginLeft: '8px' }} />
                      </div>
                      <Tooltip title="选择你想要使用的开发工具">
                        <QuestionCircleOutlined className="text-gray-400" />
                      </Tooltip>
                    </div>
                    <Form.Item
                      label="选择开发工具"
                      name={['devtools', 'ides']}
                      initialValue={['vscode', 'cursor']}
                    >
                      <Select
                        mode="multiple"
                        options={[
                          { label: 'Visual Studio Code', value: 'vscode' },
                          { label: 'Cursor', value: 'cursor' }
                        ]}
                      />
                    </Form.Item>
                  </Card>

                  {/* 基础插件配置 */}
                  <Card className="mb-6">
                    <div className="flex items-center justify-between mb-4">
                      <div className="flex items-center">
                        <span className="text-lg font-medium text-green-600">Rust 开发插件</span>
                        <Badge count="RUST" style={{ backgroundColor: '#059669', marginLeft: '8px' }} />
                      </div>
                      <Tooltip title="配置 Rust 开发所需的必要和推荐插件">
                        <QuestionCircleOutlined className="text-gray-400" />
                      </Tooltip>
                    </div>
                    <Form.Item
                      label="必选插件"
                      name={['devtools', 'requiredExtensions']}
                      initialValue={[
                        'rust-lang.rust-analyzer',
                        'vadimcn.vscode-lldb',
                        'tamasfe.even-better-toml'
                      ]}
                    >
                      <Select
                        mode="multiple"
                        disabled
                        options={[
                          { label: 'Rust Analyzer (必选)', value: 'rust-lang.rust-analyzer' },
                          { label: 'LLDB 调试器 (必选)', value: 'vadimcn.vscode-lldb' },
                          { label: 'TOML 支持 (必选)', value: 'tamasfe.even-better-toml' }
                        ]}
                      />
                    </Form.Item>

                    <Form.Item
                      label="推荐插件"
                      name={['devtools', 'recommendedExtensions']}
                      initialValue={[
                        'github.vscode-github-actions',
                        'ms-azuretools.vscode-docker',
                        'streetsidesoftware.code-spell-checker'
                      ]}
                    >
                      <Select
                        mode="multiple"
                        options={[
                          { label: 'GitHub Actions', value: 'github.vscode-github-actions' },
                          { label: 'Docker', value: 'ms-azuretools.vscode-docker' },
                          { label: '代码拼写检查', value: 'streetsidesoftware.code-spell-checker' },
                          { label: '代码运行器', value: 'formulahendry.code-runner' },
                          { label: '错误提示增强', value: 'usernamehw.errorlens' },
                          { label: '依赖检查', value: 'fill-labs.dependi' },
                          { label: 'Git 忽略文件', value: 'codezombiech.gitignore' },
                          { label: '路径智能提示', value: 'christian-kohler.path-intellisense' }
                        ]}
                      />
                    </Form.Item>
                  </Card>

                  {/* 主题和图标 */}
                  <Card className="mb-6">
                    <div className="flex items-center justify-between mb-4">
                      <div className="flex items-center">
                        <span className="text-lg font-medium text-purple-600">主题与图标</span>
                        <Badge count="UI" style={{ backgroundColor: '#8b5cf6', marginLeft: '8px' }} />
                      </div>
                      <Tooltip title="自定义开发环境的视觉外观">
                        <QuestionCircleOutlined className="text-gray-400" />
                      </Tooltip>
                    </div>
                    <Form.Item
                      label="主题插件"
                      name={['devtools', 'themeExtensions']}
                      initialValue={[
                        'BeardedBear.beardedtheme',
                        'PKief.material-icon-theme'
                      ]}
                    >
                      <Select
                        mode="multiple"
                        options={[
                          { label: 'Bearded 主题', value: 'BeardedBear.beardedtheme' },
                          { label: 'Material 图标主题', value: 'PKief.material-icon-theme' },
                          { label: 'Jellyfish 主题', value: 'PawelBorkar.jellyfish' },
                          { label: 'Tokyo Hack 主题', value: 'ajshortt.tokyo-hack' }
                        ]}
                      />
                    </Form.Item>
                  </Card>

                  {/* 远程开发 */}
                  <Card className="mb-6">
                    <div className="flex items-center justify-between mb-4">
                      <div className="flex items-center">
                        <span className="text-lg font-medium text-indigo-600">远程开发</span>
                        <Badge count="REMOTE" style={{ backgroundColor: '#4f46e5', marginLeft: '8px' }} />
                      </div>
                      <Tooltip title="配置远程开发和容器相关插件">
                        <QuestionCircleOutlined className="text-gray-400" />
                      </Tooltip>
                    </div>
                    <Form.Item
                      label="远程开发插件"
                      name={['devtools', 'remoteExtensions']}
                      initialValue={[
                        'ms-vscode-remote.remote-containers',
                        'ms-vscode-remote.remote-ssh'
                      ]}
                    >
                      <Select
                        mode="multiple"
                        options={[
                          { label: '远程容器', value: 'ms-vscode-remote.remote-containers' },
                          { label: '远程 SSH', value: 'ms-vscode-remote.remote-ssh' },
                          { label: '远程 SSH 配置', value: 'ms-vscode-remote.remote-ssh-edit' },
                          { label: '远程资源管理器', value: 'ms-vscode.remote-explorer' }
                        ]}
                      />
                    </Form.Item>
                  </Card>

                  {/* 终端设置 */}
                  <Card className="mb-6">
                    <div className="flex items-center justify-between mb-4">
                      <div className="flex items-center">
                        <span className="text-lg font-medium text-yellow-600">终端设置</span>
                        <Badge count="SHELL" style={{ backgroundColor: '#d97706', marginLeft: '8px' }} />
                      </div>
                      <Tooltip title="配置终端环境">
                        <QuestionCircleOutlined className="text-gray-400" />
                      </Tooltip>
                    </div>
                    <Form.Item
                      label="默认终端"
                      name={['devtools', 'terminal', 'defaultProfile']}
                      initialValue="zsh"
                    >
                      <Select
                        options={[
                          { label: 'Zsh', value: 'zsh' },
                          { label: 'Bash', value: 'bash' }
                        ]}
                      />
                    </Form.Item>
                    <Form.Item
                      label="终端路径"
                      name={['devtools', 'terminal', 'path']}
                      initialValue="/bin/zsh"
                    >
                      <Input placeholder="输入终端程序路径" />
                    </Form.Item>
                  </Card>

                  {/* 远程设置 */}
                  <Card>
                    <div className="flex items-center justify-between mb-4">
                      <div className="flex items-center">
                        <span className="text-lg font-medium text-red-600">远程设置</span>
                        <Badge count="CONFIG" style={{ backgroundColor: '#dc2626', marginLeft: '8px' }} />
                      </div>
                      <Tooltip title="配置远程开发环境相关设置">
                        <QuestionCircleOutlined className="text-gray-400" />
                      </Tooltip>
                    </div>
                    <Form.Item
                      label="VS Code 服务器下载地址"
                      name={['devtools', 'remote', 'serverDownloadUrl']}
                      initialValue="https://vscode.cdn.azure.cn/stable/0781e811de386a0c5bcb07ceb259df8ff8246a50/vscode-server-linux-x64.tar.gz"
                    >
                      <Input placeholder="输入 VS Code 服务器下载地址" />
                    </Form.Item>
                    <Form.Item
                      label="Docker 路径"
                      name={['devtools', 'remote', 'dockerPath']}
                      initialValue="docker"
                    >
                      <Input placeholder="输入 Docker 可执行文件路径" />
                    </Form.Item>
                    <Form.Item
                      label="Docker Compose 路径"
                      name={['devtools', 'remote', 'dockerComposePath']}
                      initialValue="docker-compose"
                    >
                      <Input placeholder="输入 Docker Compose 可执行文件路径" />
                    </Form.Item>
                  </Card>

                  {/* 底部按钮 */}
                  <div className="flex justify-end border-t border-gray-100 mt-6 pt-4">
                    <Button type="primary" size="large" onClick={handleNext}>
                      下一步 <ArrowRightOutlined />
                    </Button>
                  </div>
                </Form>
              </div>
            ),
          },
          {
            key: 'workflow',
            label: '工作流',
            children: (
              <div className="flex-1 p-4 flex flex-col">
                <WorkflowDiagram />
              </div>
            ),
          },
          {
            key: 'preview',
            label: '预览',
            children: (
              <div className="text-gray-400 text-center py-12">最终生成的配置内容将在此处预览。</div>
            ),
          },
        ]}
      />
    </div>
  );
} 